package com.tools.box.util.localpermiss

import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import androidx.core.app.ActivityCompat
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions

class PermissUtils {

    companion object {
        private var isFirst by SPreference(IS_BT_PREMISS,false)

        fun showPremissDialog(context: Context,premissListener: PremissListener) {
            if (isFirst){
                if (ActivityCompat.checkSelfPermission(context,Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                    premissListener.onSuccess()
                }else{
                    premissListener.onFail()
                }
                return
            }
            val permissDialog = PremissDialog(context, R.style.dialog)
            permissDialog.show()
            permissDialog.setOnDialogClickListener(object : PremissDialog.OnDialogClickListener{
                override fun onAgree() {
                    setReadPremiss(context,premissListener)
                    isFirst =true
                }

                override fun onCancel() {
                    isFirst =true
                    premissListener.onFail()
                }
            })
        }

        private fun setReadPremiss(context: Context,premissListener: PremissListener){
            XXPermissions.with(context)
                .permission(Permission.READ_EXTERNAL_STORAGE)
                .permission(Permission.WRITE_EXTERNAL_STORAGE)
                .permission(Permission.CAMERA)
                .request(object : OnPermissionCallback {
                    override fun onGranted(permissions: MutableList<String>?, all: Boolean) {
                        premissListener.onSuccess()
                    }

                    override fun onDenied(permissions: MutableList<String>?, never: Boolean) {
                        super.onDenied(permissions, never)
                        premissListener.onFail()
                    }
                })

        }

        interface PremissListener{
            fun onSuccess()
            fun onFail()
        }

    }
}